<template>
  <!--  试验计划-附件 查看 -->
  <div v-dialog-drag>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="40%"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      :show-close="false"
      z-index="1999"
      @close="close"
    >
      <!-- 外层dialog -->
      <el-button type="primary" size="mini" @click="innerVisible = true">新增</el-button>
      <el-table
        :data="fileList"
        border
        size="mini"
        style="width: 100%"
        center
      >
        <el-table-column
          prop="id"
          label="序号"
          width="60"
          align="center"
        />
        <el-table-column
          prop="file_type"
          label="类型"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag effect="dark" type="info">{{ scope.row.file_type === '2' ? '文件' : '图片' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="file_name"
          label="名称"
          align="center"
        />
        <el-table-column
          label="操作"
          align="center"
        >
          <template slot-scope="scope">
            <el-button
              type="success"
              size="mini"
              @click="checkInfo(scope.row)"
            >
              查看
            </el-button>
            <el-button
              type="danger"
              size="mini"
              @click="del(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        layout="prev, pager, next"
        :page-size="10"
        :current-page="formInline.offset"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="float: right;"
        :total="total">
      </el-pagination>
      <span slot="footer" class="dialog-footer">
      <el-button
        type="primary"
        size="mini"
        @click="close"
      >关闭</el-button>
    </span>
      <!-- 内层dialog -->
      <el-dialog
        width="30%"
        title="新增附件"
        :visible.sync="innerVisible"
        z-index="2000"
        append-to-body>
        <el-form ref="subForm" :model="form" label-width="100px">
          <el-form-item
            label="文件名称"
            prop="file_name"
            :rules="[
              { required: true, message: '请输入文件名称', trigger: 'blur' }
            ]"
          >
            <el-input size="mini" v-model="form.file_name"></el-input>
          </el-form-item>
          <el-form-item
            label="附件"
            prop="file_url"
            :rules="[
              { required: true, message: '请上传附件', trigger: 'blur' }
            ]"
          >
            <el-upload
              class="upload-demo"
              drag
              :data="data"
              :action="baseURL + '/admin/file/upload'"
              :headers="header"
              :on-success="handleAvatarSuccess"
              :limit="1"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="mini" @click="innerVisible = false">取 消</el-button>
          <el-button size="mini" type="primary" @click="submit">确认</el-button>
        </div>
      </el-dialog>
    </el-dialog>
    <!-- 图片预览 -->
    <el-image-viewer v-if="imgViewerVisible" :on-close="closeImgViewer" :url-list="imgList" />
  </div>
</template>

<script>
import { planFileList, addPlanFile, delPlanFile } from '@/api/operations'
import { getToken } from '@/utils/auth'
export default {
  name: 'detail',
  components: {
    'el-image-viewer': () => import('element-ui/packages/image/src/image-viewer')
  },
  props: {
    dialogVisible: {
      type: Boolean,
      default: true
    },
    title: {
      type: String,
      default: '新增'
    },
    id: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      imgViewerVisible: false, // 图片预览标识
      imgList: [], // 预览图片数据
      header: {
        'Authorization': 'Bearer ' + getToken(),
        'Lang': 'zh-CN'
      },
      data: {
        directory: 'planFile',
        name: ''
      }, // upload 传参
      baseURL: process.env.VUE_APP_BASE_API,
      innerVisible: false, // 内层dialog
      total: 0, // 文件总条数
      fileList: [], // 文件列表
      formInline: {
        offset: 1,
        limit: 10
      },
      form: {
        file_name: '',
        file_url: '',
        plan_id: '', // 关联id
        file_type: 1 // 文件类型：1图片2文件
      }
    }
  },
  created() {
    // 编辑
    if (this.id) {
      this.getFileList()
    }
  },
  methods: {
    /**
     * @description: 查看附件/图片
     * @author: 书童
     */
    checkInfo(row) {
      console.log(row.file_url)
      if (row.file_type === '1') {
        // 图片
        this.imgViewerVisible = true
        this.imgList = [row.file_url]
      } else {
        window.open('https://view.officeapps.live.com/op/view.aspx?src=' + row.file_url)
      }
    },
    /**
     * @description: 查看附件/图片
     * @author: 书童
     */
    del(id) {
      this.$confirm('是否要删除此条数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delPlanFile({ id }).then(res => {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.getFileList()
        })
      })
    },
    /**
     * @description: 提交附件
     * @author: 书童
     */
    submit() {
      this.$refs['subForm'].validate((valid) => {
        if (valid) {
        //   js判断文件是否是图片
          let num = this.form.file_url.lastIndexOf(".")
          let str = this.form.file_url.substr(num+1)
          let flag =  ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff'].indexOf(str.toLowerCase()) !== -1
          this.form.file_type = flag ? 1 : 2
          console.log('flag', flag)
          this.form.plan_id = this.id
          addPlanFile(this.form).then(res => {
            this.innerVisible = false
            this.getFileList()
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },
    /**
     * @description: 请求附件列表
     * @author: 书童
     */
    getFileList() {
      planFileList(Object.assign({},this.formInline,{plan_id: this.id})).then(res => {
        this.fileList = res.data.files
        this.total = res.data.total
      })
    },
    // 列表分页
    handleSizeChange(val) {
      this.formInline.limit = val
      this.getFileList()
    },
    handleCurrentChange(val) {
      this.formInline.offset = val
      this.getFileList()
    },
    // 文件上传
    handleAvatarSuccess(res, file) {
      this.form.file_url = res.data.realPath
    },
    // 关闭弹窗
    close() {
      this.$emit('close')
    },
    // 关闭图片预览
    closeImgViewer() {
      this.imgViewerVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    border-radius: 10px;
    border: 1px dashed #cccccc;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
    border-radius: 10px;
  }
</style>
